import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入store模块
import store from '@/store/index.js'
// 导入注册页面
import Register from '@/views/Register/Register.vue'
// 导入登录页面
import Login from '@/views/Login/Login.vue'
// 导入首页页面
import Layout from '@/views/Layout/Layout.vue'
// 导入首页下的子页图标页Home
import Home from '@/views/Layout/Home/Home.vue'
// 导入首页下的子页用户信息页
import UserInfo from '@/views/Layout/User/UserInfo.vue'
// 导入首页下的子页重置密码页
import UserRep from '@/views/Layout/User/UserRep.vue'
// 导入首页下的子页更换头像页
import UserAvatar from '@/views/Layout/User/UserAvatar.vue'
// 导入首页下的子页文章分类页
import ArtCate from '@/views/Layout/Article/ArtCate.vue'
// 导入首页下的子页文章列表页
import ArtList from '@/views/Layout/Article/ArtLsit.vue'
// 导入404页面
import Go404 from '@/views/Go404/Go404.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/register', component: Register, meta: { title: '注册' } },
  { path: '/login', component: Login, meta: { title: '登录' } },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: 'home', component: Home, meta: { title: '首页' } },
      { path: 'user-info', component: UserInfo, meta: { title: '基本资料' } },
      { path: 'user-avatar', component: UserAvatar, meta: { title: '更换头像' } },
      { path: 'user-pwd', component: UserRep, meta: { title: '重置密码' } },
      { path: 'art-cate', component: ArtCate, meta: { title: '文章分类' } },
      { path: 'art-list', component: ArtList, meta: { title: '文章列表' } }
    ]
  },
  { path: '*', component: Go404, meta: { title: 'Not Found' } }
]

const router = new VueRouter({
  routes
})
// 路由白名单
const whiteName = ['/register', '/login']
// 路由前置守卫
router.beforeEach((to, from, next) => {
  const token = store.state.userModule.token
  document.title = to.meta.title
  if (token) return next()
  if (whiteName.includes(to.path)) return next()
  next('/login')
})
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}

export default router
